const fs=require('fs');
const uuid=require('uuid');

const fileType=function(fileName){
    if(fileName.indexOf('.')!=-1){
        return fileName.split('.').pop();
    }
    return "";
}

const uploader = function (file, options) {
    if (!file) throw new Error('no file(s)');

    return _fileHandler(file, options);
}

const _fileHandler = function (file, options) {
    if (!file) throw new Error('no file');

    const orignalname = file.hapi.filename;
    const type=fileType(orignalname);
    const filename = uuid.v1()+"."+type;
    const path = `${options.dest}${filename}`;
    const fileStream = fs.createWriteStream(path);

    return new Promise((resolve, reject) => {
        file.on('error', function (err) {
            reject(err);
        });

        file.pipe(fileStream);

        file.on('end', function (err) {
            const fileDetails = {
                fieldname: file.hapi.name,
                originalname: orignalname,
                filename,
                mimetype: file.hapi.headers['content-type'],
                destination: `${options.dest}`,
                path:`${options.server}/${path}`,
                size: fs.statSync(path).size,
            }

            resolve(fileDetails);
        })
    })
}

module.exports={
    upload:uploader
}